package com.martin.lib_base.helper

import com.flyjingfish.android_aop_annotation.anno.AndroidAopCollectMethod
import com.martin.lib_base.interfaces.IAppLifeAutoListener
import com.martin.lib_base.interfaces.IAppLifeListener
import com.martin.lib_base.ktx.loge
import dev.utils.app.AppUtils
import dev.utils.app.ProcessUtils
import dev.utils.common.ReflectUtils

/**
 * @desc: 应用生命周期工具
 * @focus: 仅处理主进程逻辑
 */
object AppLifecycleHelper : IAppLifeListener {

    /**
     * 应用生命周期监听集合
     */
    private val list = arrayListOf<IAppLifeListener>(
        HeartHelper,
    )

    /**
     * 自动监听列表
     */
    private val autoList = arrayListOf<IAppLifeAutoListener>()

    /**
     * 添加监听
     */
    fun addListener(listener: IAppLifeListener) {
        list.add(listener)
    }

    override fun onAppCreate() {
        if (!isMainProcess()) return
        showLog("onAppCreate")
        list.forEach { it.onAppCreate() }
        autoList.forEach { it.onAppCreate() }
    }

    override fun onAppShow() {
        if (!isMainProcess()) return
        showLog("onAppShow")
        list.forEach { it.onAppShow() }
        autoList.forEach { it.onAppShow() }
    }

    override fun onAppHide() {
        if (!isMainProcess()) return
        showLog("onAppHide")
        list.forEach { it.onAppHide() }
        autoList.forEach { it.onAppHide() }
    }

    override fun onAppTerminate() {
        if (!isMainProcess()) return
        showLog("onAppTerminate")
        list.forEach { it.onAppTerminate() }
        autoList.forEach { it.onAppTerminate() }
    }

    /**
     * 是否为主进程
     */
    fun isMainProcess() = ProcessUtils.getCurProcessName() == AppUtils.getPackageName()

    /**
     * 收集全局 ILocationListener 实现类
     */
    @AndroidAopCollectMethod
    @JvmStatic
    fun collectListener(bean: IAppLifeAutoListener) {
        if (!isMainProcess()) return
        showLog("collectListener - ${bean.javaClass.simpleName}")
        autoList.add(bean)
    }

    /**
     * 获取自动监听器
     */
    fun getAutoListener(clazz: Class<out IAppLifeAutoListener>): IAppLifeAutoListener {
        var find = autoList.find { it.javaClass == clazz }
        if (find == null) {
            find = ReflectUtils.reflect(clazz).newInstance().get()
            autoList.add(find!!)
        }
        return find;
    }


    private fun showLog(message: String) {
        loge("App生命周期工具 - ${ProcessUtils.getCurProcessName()} : $message")
    }
}